package net.tngou.tnfs.quartz;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;









import java.util.List;

import net.tngou.tnfs.util.HttpConfig;

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.sanselan.ImageInfo;
import org.apache.sanselan.Sanselan;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EmptyTempJob implements Job {
	private static Logger _log = LoggerFactory.getLogger(EmptyTempJob.class);
	
	private static PropertiesConfiguration quartzProperties =null;
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
	
		File propertiesFile = new File("quartz.properties");
		Configurations configs = new Configurations();
		try {
			quartzProperties = configs.properties(propertiesFile);
		} catch (ConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
		}
		
		List<File> list = new ArrayList<File>();
		String temp= HttpConfig.getInstance().getTnfspath()+File.separator+"temp";
		File tempFile = new File(temp); 
		list=getFiles(tempFile ,list); //提出缓存文件
		 
		list=expirationFile(list); //提出过期文件
			 
		list.forEach(e->{delete(e);}); //删除文件
	}
	
	public static void main(String[] args) throws JobExecutionException {
		
		new EmptyTempJob().execute(null);
		
		
	}
	
	
	
	public void delete(File file) {
		
		if(file.isDirectory())
		{
			if(file.listFiles().length==0)
			{
				file.delete();
			}
				
		}else
		{
			file.delete();
		}
		
	}
	
	public List<File> expirationFile(List<File> list) {
		
		List<File> expirationFiles = new ArrayList<File>();
		Date date = DateUtils.addDays(new Date(), -quartzProperties.getInt("expirationdate"));

		for (File file : list) {
			  if(date.getTime()>file.lastModified())
					expirationFiles.add(file);
		}
		
		return expirationFiles;
		
	}
	
	
	
	/*
	  * 通过递归得到某一路径下所有的目录及其文件
	  */
	public List<File> getFiles(File tempDir,List<File> list){
	
	    File[] files = tempDir.listFiles();
	    for(File file:files){    
	     if(file.isDirectory()){
	      /*
	       * 递归调用
	       */
	    	 list= getFiles(file,list); 
	         list.add(file);
	     
	     }else{
	       list.add(file);
	     }    
	    }
	    
	    return list;
	 }
	

}
